using System;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Higgs.Web.AtomPub
{
    public static class AtomHelper
    {
        public static string MakeGlobalIRI(this HttpContextBase ctx, string id)
        {
            var str2 = ctx.Request.Url.Host.ToLower();
            if (str2.StartsWith("www.")) str2 = str2.Substring(4);

            var provider = new MD5CryptoServiceProvider();
            var guid = new Guid(provider.ComputeHash(Encoding.UTF8.GetBytes(str2 + "+" + id)));

            return ("urn:uuid:" + guid);
        }

        public static string ToAbsoluteUrl(this string relativeUrl)
        {
            var request = HttpContext.Current.Request;
            var protocol = request.IsSecureConnection ? "https" : "http";
            var appPath = request.ApplicationPath == "/" ? "" : request.ApplicationPath;
            var result = String.Format("{0}://{1}/{2}", protocol, request.Url.Authority + appPath, relativeUrl);

            return result.EndsWith("/") ? result.Substring(0, result.Length - 1) : result;
        }

        public static string RemoveUrlParameter(this string url)
        {
            var index = url.IndexOf("{");
            var result = index < 0 ? url : url.Substring(0, index);

            return !result.EndsWith("/") ? result + "/" : result;
        }
    }
}